package Com.Ring.TradingMobile;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import Com.Ring.TradingMobile.Lib.Common;
import Com.Ring.TradingMobile.Object.CompanyInfo;
import Com.Ring.TradingMobile.Object.StockInfo;
import Com.Ring.TradingMobile.SQLite.DBManager;
import Com.Ring.TradingMobile.Service.WebService;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TableRow.LayoutParams;

public class HistoryActivity extends Activity {

	private final static String TAG = "History";

	private TextView txtFromDate;
	private TextView txtToDate;
	private TextView txtStock;

	private int FromYear;
	private int FromMonth;
	private int FromDay;
	private int ToYear;
	private int ToMonth;
	private int ToDay;

	static final int FROM_DATE_DIALOG_ID = 0;
	static final int TO_DATE_DIALOG_ID = 1;
	static final int DIALOG_LOADING = 3;

	private Button btnXem;
	private Button btnFromDate;
	private Button btnToDate;
	
	private Button btnBack;
	private Button btnHome;
	private Button btnRefresh;

	private LinearLayout linearHeader;
	private LinearLayout linearContent;

	private AutoCompleteTextView AutoCompleteStock;

	private String Code = "";

	private Handler updaterHandler;
	private ExecutorService updaterExecutor;
	private Runnable updaterRunnable = null;
	private Future<?> updaterFuture;

	public boolean IsUpdateCompany;
	public boolean IsUpdateStockInfoRunning;
	public boolean IsRunningUpdate;

	private int[] StrHeaderId = new int[]{R.string.strDate, R.string.strRef,
			R.string.strCeiling, R.string.strFloor, R.string.strLast,
			R.string.strChange, R.string.strVol, R.string.strBestBuyPrice,
			R.string.strBestBuyVol, R.string.strBestSellPrice,
			R.string.strBestSellVol, R.string.strTotalVol};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.history);
		FindViewId();
		BindingData();
		SetOnListener();
		InitThread();
		final Calendar c = Calendar.getInstance();
		ToYear = FromYear = c.get(Calendar.YEAR);
		ToMonth = FromMonth = c.get(Calendar.MONTH);
		ToDay = FromDay = c.get(Calendar.DAY_OF_MONTH);
		updateDisplayFrom();
		updateDisplayTo();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		Common.StopTimer();

		try {
			updaterExecutor.shutdown();
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
		super.onPause();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
		IsUpdateCompany = true;
		Runnable runable = new Common.CountDownRunner();
		Common.StartTimer(runable, HistoryActivity.this);
		txtStock.setText("");
		UpdateTask(1);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	private void FindViewId() {
		txtFromDate = (TextView) findViewById(R.id.lblFromDate);
		txtToDate = (TextView) findViewById(R.id.lblToDate);
		txtStock = (TextView) findViewById(R.id.lblStock);
		btnFromDate = (Button) findViewById(R.id.btnFromDate);
		btnToDate = (Button) findViewById(R.id.btnToDate);
		btnXem = (Button) findViewById(R.id.btnXem);
		
		
		btnBack = (Button)findViewById(R.id.btnBack);
		btnHome = (Button)findViewById(R.id.btnHome);
		btnRefresh = (Button)findViewById(R.id.btnRefresh);

		linearHeader = (LinearLayout) findViewById(R.id.linearHeader);
		linearContent = (LinearLayout) findViewById(R.id.linearContent);
		AutoCompleteStock = (AutoCompleteTextView) findViewById(R.id.autoCompleteMarket);
		AutoCompleteStock.setThreshold(1);

		TableLayout tableHeader = new TableLayout(this);
		TableRow[] rowsHeader = new TableRow[StrHeaderId.length];
		TextView[] txtHeader = new TextView[StrHeaderId.length];
		for (int i = 0; i < txtHeader.length; i++) {
			rowsHeader[i] = new TableRow(this);
			txtHeader[i] = new TextView(this);
			txtHeader[i].setText(StrHeaderId[i]);
			txtHeader[i].setHeight(24);
			txtHeader[i].setTextSize(12);
			txtHeader[i]
					.setBackgroundResource(R.drawable.border_color_textview);
			txtHeader[i].setTextColor(getResources().getColor(R.color.whiles));
			rowsHeader[i].addView(txtHeader[i]);
			tableHeader.addView(rowsHeader[i]);
		}
		linearHeader.addView(tableHeader);
		
		

		
		btnBack.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(),
						TradingMobileActivity.class);
				startActivity(intent);
				finish();
			}
		});
		
		btnHome.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(),
						TradingMobileActivity.class);
				startActivity(intent);
				finish();
			}
		});
		
		
		btnRefresh.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

			}
		});
	}
	private void BindingData() {

	}

	private void SetOnListener() {
		btnFromDate.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showDialog(FROM_DATE_DIALOG_ID);
			}
		});
		btnToDate.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showDialog(TO_DATE_DIALOG_ID);
			}
		});
		btnXem.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Code = AutoCompleteStock.getText().toString().trim();
				if(!Code.equals("")&& Code.length()>=3) {
					AutoCompleteStock.setText("");
					txtStock.setText(Code);
					UpdateTask(1);
				}
			}
		});
	}
	private void updateDisplayFrom() {
		txtFromDate.setText(new StringBuilder().append(pad(FromDay))
				.append("-").append(pad(FromMonth + 1)).append("-")
				.append(FromYear));
	}
	private void updateDisplayTo() {
		txtToDate.setText(new StringBuilder().append(pad(ToDay)).append("-")
				.append(pad(ToMonth + 1)).append("-").append(ToYear));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case FROM_DATE_DIALOG_ID :
				return new DatePickerDialog(this, FromDateSetListener,
						FromYear, FromMonth, FromDay);

			case TO_DATE_DIALOG_ID :
				return new DatePickerDialog(this, ToDateSetListener, ToYear,
						ToMonth, ToDay);
			case DIALOG_LOADING :
				ProgressDialog dialog = new ProgressDialog(this);
				dialog.setMessage("Please wait while loading...");
				dialog.setIndeterminate(true);
				dialog.setCancelable(true);
				return dialog;
		}
		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
			case FROM_DATE_DIALOG_ID :
				((DatePickerDialog) dialog).updateDate(FromYear, FromMonth,
						FromDay);
				break;
			case TO_DATE_DIALOG_ID :
				((DatePickerDialog) dialog).updateDate(ToYear, ToMonth, ToDay);
				break;
		}
	}

	private DatePickerDialog.OnDateSetListener FromDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			FromYear = year;
			FromMonth = monthOfYear;
			FromDay = dayOfMonth;
			updateDisplayFrom();
		}
	};
	private DatePickerDialog.OnDateSetListener ToDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			ToYear = year;
			ToMonth = monthOfYear;
			ToDay = dayOfMonth;
			updateDisplayTo();
		}
	};

	public void ShowDialog() {
		updaterHandler.post(new Runnable() {
			public void run() {
				showDialog(DIALOG_LOADING);
			}
		});
	}

	public void RemoveDialog() {
		updaterHandler.post(new Runnable() {
			public void run() {
				removeDialog(DIALOG_LOADING);
			}
		});
	}

	public void UpdateCompany(List<CompanyInfo> listCompany) {
		if (listCompany.size() > 0) {
			String[] arrayCode = new String[listCompany.size()];
			int i = 0;
			for (CompanyInfo company : listCompany) {
				arrayCode[i++] = company.Code;
			}
			try {
				UpdateCompanyUIThread(arrayCode, AutoCompleteStock);

			} catch (Exception ex) {
				Log.d(TAG, ex.toString());
			}
		}
	}

	private void UpdateCompanyUIThread(final String[] arrayCode,
			final AutoCompleteTextView auto) {
		updaterHandler.post(new Runnable() {
			public void run() {
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(
						HistoryActivity.this,
						android.R.layout.simple_dropdown_item_1line, arrayCode);
				auto.setAdapter(adapter);
			}
		});
	}
	private void InitThread() {
		updaterHandler = new Handler();
		updaterExecutor = Executors.newSingleThreadExecutor();
		updaterRunnable = new Runnable() {
			public void run() {
				Log.d(TAG, "Running....");
				if (updaterFuture != null) {
					updaterFuture.cancel(true);
				}
				HistoryTask historyTask = new HistoryTask(HistoryActivity.this,
						Code, FromYear + "-" + pad(FromMonth + 1) + "-"
								+ pad(FromDay), ToYear + "-" + pad(ToMonth + 1)
								+ "-" + pad(ToDay));
				updaterFuture = updaterExecutor.submit(historyTask);
			}
		};
	}
	private void UpdateTask(int delay) {
		updaterHandler.removeCallbacks(updaterRunnable);
		updaterHandler.postDelayed(updaterRunnable, delay);
	}

	public void UpdateListStockInfo(List<StockInfo> listStockInfo) {
		try {
			Log.d(TAG, "Running Create Table Content ");
			UpdateStockInfoUIThread(linearContent, listStockInfo);
			Log.d(TAG, "Done create Table Content");
		} catch (Exception ex) {
			Log.d(TAG, ex.toString());
		}
	}

	private void UpdateStockInfoUIThread(final LinearLayout linearContent,
			final List<StockInfo> listStockInfo) {
		updaterHandler.post(new Runnable() {
			public void run() {
				if (listStockInfo != null && listStockInfo.size() > 0) {
					linearContent.removeAllViewsInLayout();
					String text = null;
					int color = 0;
					for (StockInfo stockInfo : listStockInfo) {
						TableLayout tableContent = new TableLayout(
								HistoryActivity.this);
						TableRow[] rowContents = new TableRow[StrHeaderId.length];
						TextView[] txtContent = new TextView[StrHeaderId.length];
						for (int i = 0; i < txtContent.length; i++) {
							rowContents[i] = new TableRow(HistoryActivity.this);
							txtContent[i] = new TextView(HistoryActivity.this);
							// set text
							switch (i) {
								case 0 :
									text = stockInfo.TradeDate;
									color = R.color.whiles;
									break;
								case 1 :
									text = Common
											.FormatNumber(stockInfo.RefPrice);
									color = R.color.nochange;
									break;
								case 2 :
									text = Common
											.FormatNumber(stockInfo.CeilPrice);
									color = R.color.ceilling;
									break;
								case 3 :
									text = Common
											.FormatNumber(stockInfo.FloorPrice);
									color = R.color.floor;
									break;
								case 4 :
									text = Common
											.FormatNumber(stockInfo.PriceMatch);
									color = SetColorStockInfo(
											stockInfo.PriceMatch,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 5 :
									text = Common
											.FormatNumber(stockInfo.Changed);
									color = SetColorStockInfo(
											stockInfo.PriceMatch,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 6 :
									text = Common
											.FormatNumber(stockInfo.VolumeMatch);
									color = SetColorStockInfo(
											stockInfo.PriceMatch,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 7 :
									text = Common
											.FormatNumber(stockInfo.BestPriceBuy);
									color = SetColorStockInfo(
											stockInfo.BestPriceBuy,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 8 :
									text = Common
											.FormatNumber(stockInfo.BestVolbuy);
									color = SetColorStockInfo(
											stockInfo.BestPriceBuy,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 9 :
									text = Common
											.FormatNumber(stockInfo.BestPriceSell);
									color = SetColorStockInfo(
											stockInfo.BestPriceSell,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 10 :
									text = Common
											.FormatNumber(stockInfo.BestVolSell);
									color = SetColorStockInfo(
											stockInfo.BestPriceSell,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
								case 11 :
									text = Common
											.FormatNumber(stockInfo.TotalMatch);
									color = SetColorStockInfo(
											stockInfo.PriceMatch,
											stockInfo.CeilPrice,
											stockInfo.FloorPrice,
											stockInfo.RefPrice);
									break;
							}
							txtContent[i].setText(text);
							txtContent[i].setTextColor(getResources().getColor(
									color));
							txtContent[i].setHeight(24);
							txtContent[i].setTextSize(12);
							txtContent[i].setGravity(Gravity.RIGHT);
							txtContent[i].setPadding(0, 0, 2, 0);
							LayoutParams layout = new LayoutParams(
									LayoutParams.WRAP_CONTENT,
									LayoutParams.WRAP_CONTENT);
							// layout.width = 50;
							txtContent[i].setLayoutParams(layout);

							txtContent[i]
									.setBackgroundResource(R.drawable.border_color_textview);
							rowContents[i].addView(txtContent[i], layout);
							tableContent.addView(rowContents[i]);
						}
						// add row virtual
						TableRow rowVirtual = new TableRow(HistoryActivity.this);
						tableContent.addView(rowVirtual);
						//
						linearContent.addView(tableContent);
					}
				}
			}

			private int SetColorStockInfo(float price, float ceil, float floor,
					float ref) {
				int color = 0;

				if (price == ceil)
					color = R.color.ceilling;
				else if (price == ref)
					color = R.color.nochange;
				else if (price == floor)
					color = R.color.floor;
				else if (price > ref)
					color = R.color.up;
				else if (price > floor)
					color = R.color.down;
				else
					color = R.color.whiles;

				return color;
			}
		});
	}
	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

}
